using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using FimetContoDeposito.BLL.Objects;
using GrayParrot.Web.Security;
using Newtonsoft.Json.Linq;

namespace FimetContoDeposito.Controllers
{
    public class AuthenticationController : AuthenticationControllerBase
    {
        [HttpPost]
        public HttpResponseMessage CheckLogin(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            dynamic json = data;
            string m_username = json.username.ToString();
            string m_password = json.password.ToString();

            ResponseBag m_rb = new ResponseBag();
            if (!string.IsNullOrWhiteSpace(m_username) && !string.IsNullOrWhiteSpace(m_password))
            {
                bool m_validate = Membership.ValidateUser(m_username, m_password);

                if (m_validate)
                {
                    m_rb.Msg = "User Validated !";
                    m_rb.Status = true;

                    string[] m_roles = Roles.GetRolesForUser(m_username);

                    //RolePrincipal principal = new RolePrincipal(new GenericIdentity(m_username));
                    GenericPrincipal principal = new GenericPrincipal(new GenericIdentity(m_username), m_roles);
                    
                    Thread.CurrentPrincipal = principal;
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = Thread.CurrentPrincipal;

                        Request.GetRequestContext().Principal = principal;
                    }

                    FormsAuthentication.SetAuthCookie(m_username, false);
                }
                else
                {
                    m_rb.Msg = "User not validated !";
                    m_rb.Status = false;
                }
            }

            retValue = Request.CreateResponse(HttpStatusCode.OK, m_rb);

            return retValue;
        }

        [HttpPost]
        public HttpResponseMessage LogOut(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            string m_name = HttpContext.Current.User.Identity.Name;

            FormsAuthentication.SignOut();

            ResponseBag m_rb = new ResponseBag();
            m_rb.Msg = string.Format("User {0} logout !", m_name);
            m_rb.Status = false;

            retValue = Request.CreateResponse(HttpStatusCode.OK, m_rb);

            return retValue;
        }
    }
}
